package com.zzw.service.Impl;

import com.zzw.bean.*;
import com.zzw.dao.MenuMapper;
import com.zzw.dao.MenuRolesMapper;
import com.zzw.dao.PermissionsMapper;
import com.zzw.dao.RolesMapper;
import com.zzw.dao.UserRolesMapper;
import com.zzw.service.RolesService;
import com.zzw.service.PermissionsService;
import com.zzw.config.CustomRealm;
import com.zzw.utils.RedisUtil;
import com.zzw.utils.SpringContextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 赵志伟
 * @version 1.0
 */
@SuppressWarnings({"all"})
@Service
public class RolesServiceImpl implements RolesService {

    @Autowired
    private RolesMapper rolesMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private MenuRolesMapper menuRolesMapper;
    @Autowired
    private UserRolesMapper userRolesMapper;
    @Autowired
    private PermissionsMapper permissionsMapper;
    @Autowired
    private PermissionsService permissionsService;

    // 超级管理员角色名称
    private static final String SUPER_ADMIN_ROLE = "超级管理员";

    @Override
    public List<Roles> selectRolesList(Roles roles) {
        return rolesMapper.selectRolesList(roles);
    }


    @Override
    public List<Roles> selectRolesByUserId(Integer userId) {
            return rolesMapper.selectRolesByUserId(userId);
    }

    @Override
    public boolean insert(Roles roles) {
        boolean insertResult = rolesMapper.insertSelective(roles) > 0;

        if (insertResult && roles.getPermissionsIds() != null && roles.getPermissionsIds().length > 0) {
            // 转换为List<Integer>
            List<Integer> permissionIdList = Arrays.asList(roles.getPermissionsIds());
            permissionsService.saveRolePermissions(roles.getId(), permissionIdList);
        }

        return insertResult;
    }

    @Override
    public boolean update(Roles roles) {
        // 更新角色基本信息
        rolesMapper.updateByPrimaryKeySelective(roles);

        // 保存菜单关联
        boolean menuResult = insertMenuRoles(roles);

        // 保存权限关联
        boolean permissionResult = true;
        if (roles.getPermissionsIds() != null && roles.getPermissionsIds().length > 0) {
            // 转换为List<Integer>
            List<Integer> permissionIdList = Arrays.asList(roles.getPermissionsIds());
            permissionResult = permissionsService.saveRolePermissions(roles.getId(), permissionIdList);
        } else {
            // 如果没有选择权限，则清空该角色的所有权限
            List<Integer> emptyList = new ArrayList<>();
            permissionResult = permissionsService.saveRolePermissions(roles.getId(), emptyList);
        }

        try {
            // 获取 Shiro 自定义 Realm
            CustomRealm customRealm = SpringContextUtils.getBean(CustomRealm.class);
            if (customRealm != null) {
                // 清除缓存
                customRealm.clearCache();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return menuResult && permissionResult;
    }

    @Override
    public boolean delete(Integer id) {
        return rolesMapper.deleteByPrimaryKey(id) > 0;
    }

    public boolean insertMenuRoles(Roles roles) {
        //先删除关联表的全部数据
        MenuRolesExample menuRolesExample = new MenuRolesExample();
        menuRolesMapper.deleteByExample(menuRolesExample);

        //插入数据
        Integer rolesId = roles.getId();
        String[] menusId = roles.getMenusId();

        MenuRolesKey menuRolesKey = new MenuRolesKey();
        menuRolesKey.setRoleId(rolesId);//角色id
        try {
            for (String menuId : menusId) {
                menuRolesKey.setMenuId(Integer.valueOf(menuId));//菜单id
                menuRolesMapper.insert(menuRolesKey);//角色菜单表
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return true;
    }

    /**
     * 获取用户的权限列表
     * @param userId 用户ID
     * @return 权限标识列表
     */
    @Override
    public List<String> getUserPermissions(Integer userId) {
        // 首先获取用户的所有角色
        List<Roles> roles = selectRolesByUserId(userId);

        // 检查是否为超级管理员
        boolean isSuperAdmin = false;
        for (Roles role : roles) {
            if (SUPER_ADMIN_ROLE.equals(role.getName())) {
                isSuperAdmin = true;
                break;
            }
        }

        // 如果是超级管理员，返回所有权限
        if (isSuperAdmin) {
            List<String> allPermissions = new ArrayList<>();
            List<Permissions> permissions = permissionsMapper.selectAllPermissions();
            for (Permissions permission : permissions) {
                allPermissions.add(permission.getName());
            }
            // 添加通配符权限
            allPermissions.add("*");
            return allPermissions;
        }

        // 存储所有权限
        List<String> permissions = new ArrayList<>();

        // 遍历角色，获取所有权限
        for (Roles role : roles) {
            // 查询角色对应的权限
            List<Permissions> rolePermissions = permissionsMapper.selectPermissionByRoleId(role.getId());

            // 将权限名称添加到列表中
            for (Permissions permission : rolePermissions) {
                if (!permissions.contains(permission.getName())) {
                    permissions.add(permission.getName());
                }
            }
        }

        return permissions;
    }
}

